//
//  AppDelegate.m
//  NewPro
//
//  Created by 何荧红 on 2018/10/1.
//  Copyright © 2018 何荧红. All rights reserved.
//

#import "AppDelegate.h"
#import <UMCommon/UMCommon.h>
#import <UMPush/UMessage.h>
#import <UserNotifications/UserNotifications.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "MainTabbarController.h"
#import "WelcomeViewController.h"
#import "LoginViewController.h"
#import "UserDefaultsManager.h"
#import "IQKeyboardManager.h"
//逸创云
#import "KF5SDK.h"
#import <KF5SDKCore/KF5SDKCore.h>
#import "KFUserManager.h"
#import "LoginStore.h"

@interface AppDelegate ()<TencentSessionDelegate,QQApiInterfaceDelegate,WXApiDelegate,UNUserNotificationCenterDelegate>
@property (nonatomic, strong) UserDefaultsManager *userManager;
@property (nonatomic, strong) TencentOAuth *qqOAuth;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //畅享2.0版本
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.userManager = [UserDefaultsManager sharedInstance];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.userManager.user_id = [defaults objectForKey:@"id"];
    self.userManager.user_pwd = [defaults objectForKey:@"pwd"];
    self.userManager.real_name = [defaults objectForKey:@"realname"];
    self.userManager.user_name = [defaults objectForKey:@"username"];
    self.userManager.user_avatar = [defaults objectForKey:@"headImage"];
    self.userManager.user_mobile = [defaults objectForKey:@"phoneNumber"];
    if ([self isFirstLoad]) {
        
        WelcomeViewController *welcomeview=[[WelcomeViewController alloc]init];
        self.window.rootViewController = welcomeview;
    }else{
        if (!self.userManager.user_id) {
            LoginViewController *LoVC = [[LoginViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
            self.window.rootViewController = nav;
        }else{
            
            MainTabbarController *TAB = [[MainTabbarController alloc]init];
            self.window.rootViewController = TAB;
        }
    }
    if ([UMAppkey length] > 0) {
        [UMConfigure initWithAppkey:UMAppkey channel:@"App Store"];
        // Push's basic setting
        UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
        //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
        entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert|UMessageAuthorizationOptionSound;
//        //如果你期望使用交互式(只有iOS 8.0及以上有)的通知，请参考下面注释部分的初始化代码
//        if (([[[UIDevice currentDevice] systemVersion]intValue]>=8)&&([[[UIDevice currentDevice] systemVersion]intValue]<10)) {
//            UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
//            action1.identifier = @"action1_identifier";
//            action1.title=@"打开应用";
//            action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
//            UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
//            action2.identifier = @"action2_identifier";
//            action2.title=@"忽略";
//            action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
//            action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
//            action2.destructive = YES;
//            UIMutableUserNotificationCategory *actionCategory1 = [[UIMutableUserNotificationCategory alloc] init];
//            actionCategory1.identifier = @"category1";//这组动作的唯一标示
//            [actionCategory1 setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
//            NSSet *categories = [NSSet setWithObjects:actionCategory1, nil];
//            entity.categories=categories;
//        }
//        //如果要在iOS10显示交互式的通知，必须注意实现以下代码
//        if ([[[UIDevice currentDevice] systemVersion]intValue]>=10) {
//            UNNotificationAction *action1_ios10 = [UNNotificationAction actionWithIdentifier:@"action1_identifier" title:@"打开应用" options:UNNotificationActionOptionForeground];
//            UNNotificationAction *action2_ios10 = [UNNotificationAction actionWithIdentifier:@"action2_identifier" title:@"忽略" options:UNNotificationActionOptionForeground];
//            //UNNotificationCategoryOptionNone
//            //UNNotificationCategoryOptionCustomDismissAction  清除通知被触发会走通知的代理方法
//            //UNNotificationCategoryOptionAllowInCarPlay       适用于行车模式
//            UNNotificationCategory *category1_ios10 = [UNNotificationCategory categoryWithIdentifier:@"category1" actions:@[action1_ios10,action2_ios10]   intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
//            NSSet *categories = [NSSet setWithObjects:category1_ios10, nil];
//            entity.categories=categories;
//        }
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
        [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                //点击允许
                //这里可以添加一些自己的逻辑
            }else{
                //点击不允许
                //这里可以添加一些自己的逻辑
            }
        }];
    }
    [self configOtherlink];
    //开启键盘自动管理
    [self keyBoardManager];  
    
    return YES;
}
#pragma mark - 第三方配置
- (void)configOtherlink{
    if ([WeixinAppId length] > 0) {
        [WXApi registerApp:WeixinAppId];
    }
    if ([QQAppId length] > 0) {
//        self.qqOAuth = [[TencentOAuth alloc] initWithAppId:QQAppId andDelegate:self];
        [[TencentOAuth alloc] initWithAppId:QQAppId andDelegate:self];
    }
//    逸创云
//    [KFUserManager initializeWithHostName:YiCUrl appId:YiCKey];
    [[KFConfig shareConfig]initializeWithHostName:YiCUrl appId:YiCKey];
    
}
#pragma mark - 判断是否第一次启动APP
- (BOOL) isFirstLoad{
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FristSetupTag"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"OK" forKey:@"FristSetupTag"];
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - 判断是否为最新版本
- (void)GetNewVersion{
    [self.userManager iSNewVersionSuccess:^(NSDictionary * _Nonnull res) {
        NSLog(@"%@",res);
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"%@",[HttpTool handleError:error]);
    }];
}
#pragma mark - 设置IQKeyboardManager
- (void)keyBoardManager{
    
    //键盘管理
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
    
}

#pragma mark - 支付宝回调或者微信支付回调
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    
    //微信支付开启
    if ([url.scheme isEqualToString:WeixinAppId]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                
                [self postAlipayNotiWithStatus:@"alipaySuccess"];
                
            }else{
                
                 [self postAlipayNotiWithStatus:@"alipayFailure"];
            }
        }];
    }
    
    if ([url.scheme isEqualToString:@"tencent101518370"]) {
        
        // 如果需要获取qq分享结果的回调就在这里设置代理
        return [QQApiInterface handleOpenURL:url delegate:self];
    }
    
    //微信支付开启
    if ([url.scheme isEqualToString:WeixinAppId]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

- (void)postAlipayNotiWithStatus:(NSString *)status{
    
    NSNotification *notification = [NSNotification notificationWithName:Notify_ZFB object:status];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
}

//iOS10以下使用这两个方法接收通知，
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
        //接受到数据的字典
//        self.userInfo = userInfo;
        //定制自定的的弹出框
        if([UIApplication sharedApplication].applicationState == UIApplicationStateActive){
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
                                                                message:@"Test On ApplicationStateActive"
                                                               delegate:self
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
    
            [alertView show];
        }
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    //接受到数据的字典
//        self.userInfo = userInfo;
        //定制自定的的弹出框
        if([UIApplication sharedApplication].applicationState == UIApplicationStateActive){
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题" message:@"Test On ApplicationStateActive" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
}
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}
//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
    }
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *device = [[[[deviceToken description]stringByReplacingOccurrencesOfString:@"<" withString:@""]stringByReplacingOccurrencesOfString:@" " withString:@""]stringByReplacingOccurrencesOfString:@">" withString:@""];
    NSLog(@"device = %@",device);
    _userManager.deviceToken = device;
    [self UpDateWithYiC];
    [self updateWithDeviceToken];
}
//更新或者初始化逸创云
- (void)UpDateWithYiC{
    if (self.userManager.user_name) {
        KFUser *user = [KFUserManager shareUserManager].user;
        user = [KFUser userWithDict:@{@"userToken":self.userManager.deviceToken,@"phone":self.userManager.user_name,@"userName":self.userManager.real_name}];
        [[KFUserManager shareUserManager] setUser:user];
        [[KFUserManager shareUserManager] initializeWithParams:@{KF5Email:[NSString stringWithFormat:@"%@@forcard.com",self.userManager.user_id],KF5Phone:self.userManager.user_name,KF5Name:self.userManager.real_name} completion:^(KFUser * _Nullable user, NSError * _Nullable error) {
            NSLog(@"%@",error);
        }];
    }
}
- (void)updateWithDeviceToken {
    if ([_userManager.deviceToken length] > 0 && _userManager.user_id) {
        [[[LoginStore alloc]init] updateWithDeviceToken];
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


//微信 qq的回调
- (void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[SendMessageToQQResp class]] && resp.type == ESENDMESSAGETOQQRESPTYPE)
    {
        SendMessageToQQResp* sendReq = (SendMessageToQQResp*)resp;
        // sendReq.result->0分享成功 -4取消分享
        if ([sendReq.result integerValue] == 0) {
            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"MineSureBlock" object:nil]];
            NSLog(@"QQ share success");
        }else{
            NSLog(@"QQ share failed");
        }
    }else if([resp isKindOfClass:[SendMessageToWXResp class]]){//判断是微信消息的回调 --> 是支付回调回来的还是消息回调回来的.
        if (resp.errCode == 0) {
            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"MineSureBlock" object:nil]];
            NSLog(@"微信 share success");
        }else{
            NSLog(@"微信 share failed");
        }
    }else if ([resp isKindOfClass:[PayResp class]]){
        NSString * wxPayResult;
        //支付返回的结果, 实际支付结果需要去微信服务器端查询
        switch (resp.errCode)
        {
            case WXSuccess:
            {
                NSLog(@"支付成功: %d",resp.errCode);
                wxPayResult = @"alipaySuccess";//参照支付宝支付成功
                break;
            }
            case WXErrCodeUserCancel:
            {
                NSLog(@"用户取消支付: %d",resp.errCode);
                wxPayResult = @"alipayFailure";
                break;
            }
            default:
            {
                NSLog(@":支付失败: code: %d str: %@",resp.errCode,resp.errStr);
                wxPayResult = @"alipayFailure";
                break;
            }
        }
        [self postAlipayNotiWithStatus:wxPayResult];
    }
        
    
}

@end
